package com.jeecg.study.common.utils;
/**
 * @see 解析xml文件，填充到 XmlBeans 实体中
 * @author wuhn
 * @date 2018年4月28日 17:32:47
 */

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import com.jeecg.study.entity.XmlBeans;

public class XmlUtilsNew {
	
	private static final SAXBuilder builder=new SAXBuilder();
	
	private static Document document ;
	
	/**
	 * @see 获取xml文件map映射  k-v : url - xmlBeans
	 * @param xmlPath
	 * @return
	 */
	public static Map<String, XmlBeans> readXMlFile(String xmlPath){
		Map<String, XmlBeans> map = new HashMap<>();
		if(StringUtils.isBlank(xmlPath)){
			xmlPath="src/main/resources/jeecgMVC.xml";
		}
		initDocument(xmlPath);
		Element rootNode = document.getRootElement();
		// 获取 formDataMap
		Map<String, String> formDataMap = getFormDataMap(rootNode,"formDatas");
		List<Element> actionList = rootNode.getChild("actions").getChildren();
		for (Element action : actionList) {
			XmlBeans xmlBeans=new XmlBeans();
			Map<String,String> resultMap=new HashMap<>();
			xmlBeans.setActionId(action.getAttributeValue("id"));
			xmlBeans.setActionUrl(action.getAttributeValue("url"));
			xmlBeans.setActionClass(action.getAttributeValue("class"));
			List<Element> resultList = action.getChildren();
			for (Element result : resultList) {
				resultMap.put(result.getAttributeValue("name"), result.getText());
			}
			xmlBeans.setResultMap(resultMap);
			xmlBeans.setFormDataId(xmlBeans.getActionId());
			xmlBeans.setFormDataClass(formDataMap.get(xmlBeans.getActionId()));
			map.put(action.getAttributeValue("url"), xmlBeans);
			//System.out.println(xmlBeans);
		}
		
		// System.out.println(map);
		return map;
	}
	
	
	/**
	 * @see 获取FormDatas 节点Map
	 * @param rootNode 根节点
	 * @param childNodeNames 二级节点名称
	 */
	private static Map<String,String> getFormDataMap(Element rootNode, String childNodeNames) {
		Map<String,String> map=new HashMap<>();
		List<Element> formDataList = rootNode.getChild(childNodeNames).getChildren();
		for (Element formData : formDataList) {
			map.put(formData.getAttributeValue("id"),formData.getAttributeValue("class") );
		}
		return map;
	}


	/**
	 * @see 初始化 Document 文档对象
	 * @param xmlPath
	 */
	private static void initDocument(String xmlPath) {
		try {
			document = builder.build(new File(xmlPath));
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		readXMlFile("");
	}
}
